import os
from datetime import timedelta
from dotenv import load_dotenv


load_dotenv()


def _build_sqlalchemy_uri() -> str:
	"""Build SQLAlchemy database URI from .env variables.

	DB_TYPE: sqlite (default) | postgres | mysql
	For postgres/mysql requires DB_USER, DB_PASS, DB_HOST, DB_PORT, DB_NAME
	"""
	db_type = os.getenv("DB_TYPE", "sqlite").lower()
	if db_type == "sqlite":
		# Default to local sqlite file
		db_path = os.getenv("SQLITE_PATH", os.path.join(os.getcwd(), "rbac.sqlite3"))
		return f"sqlite:///{db_path}"
	
	user = os.getenv("DB_USER", "")
	password = os.getenv("DB_PASS", "")
	host = os.getenv("DB_HOST", "localhost")
	port = os.getenv("DB_PORT", "")
	name = os.getenv("DB_NAME", "rbac")

	if db_type == "postgres":
		# psycopg2
		port = port or "5432"
		return f"postgresql+psycopg2://{user}:{password}@{host}:{port}/{name}"
	if db_type == "mysql":
		# PyMySQL
		port = port or "3306"
		return f"mysql+pymysql://{user}:{password}@{host}:{port}/{name}?charset=utf8mb4"

	raise ValueError(f"Unsupported DB_TYPE: {db_type}")


class BaseConfig:
	SECRET_KEY = os.getenv("SECRET_KEY", "dev-secret-key-change-me")
	SECURITY_PASSWORD_SALT = os.getenv("SECURITY_PASSWORD_SALT", "dev-salt-change-me")
	SQLALCHEMY_DATABASE_URI = _build_sqlalchemy_uri()
	SQLALCHEMY_TRACK_MODIFICATIONS = False
	PROPAGATE_EXCEPTIONS = True

	# JWT Settings
	JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY", SECRET_KEY)
	JWT_ACCESS_TOKEN_EXPIRES = timedelta(minutes=int(os.getenv("JWT_ACCESS_MINUTES", "30")))
	JWT_REFRESH_TOKEN_EXPIRES = timedelta(days=int(os.getenv("JWT_REFRESH_DAYS", "7")))

	# Swagger Authorizations
	RESTX_MASK_SWAGGER = False
	ERROR_404_HELP = False

	# Pagination
	PAGE_SIZE = int(os.getenv("PAGE_SIZE", "20"))


class DevelopmentConfig(BaseConfig):
	DEBUG = True
	ENV = "development"


class ProductionConfig(BaseConfig):
	DEBUG = False
	ENV = "production"


def get_config(env_name: str):
	env_name = (env_name or os.getenv("FLASK_ENV", "development")).lower()
	if env_name in ("prod", "production"):
		return ProductionConfig
	return DevelopmentConfig


